package com.tdk.wifidirectserver.receiver

import android.annotation.SuppressLint
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.NetworkCapabilities
import android.net.wifi.p2p.WifiP2pDevice
import android.net.wifi.p2p.WifiP2pManager
import android.os.Build
import android.os.Parcelable
import android.text.TextUtils
import android.util.Log
import com.tdk.wifidirectserver.inter.WifiDirectActionListener
import com.tdk.wifidirectserver.util.ConnectivityUtil

@SuppressLint("MissingPermission")
class DirectBroadcastReceiver(
    private val mWifiP2pManager: WifiP2pManager,
    private val mChannel: WifiP2pManager.Channel,
    private val mWifiDirectActionListener: WifiDirectActionListener
) : BroadcastReceiver() {


    override fun onReceive(context: Context, intent: Intent) {
//        Log.i(TAG, "接收到广播： " + intent.action)
        if (!TextUtils.isEmpty(intent.action)) {
            when (intent.action) {
                // wifi p2p状态发生改变 例如开启/关闭
                WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION -> {
                    Log.i(TAG, "WIFI_P2P_STATE_CHANGED_ACTION")
                    // 判断wifi p2p是否可用
                    val state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1)
                    if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) {
                        mWifiDirectActionListener.wifiP2pEnabled(true)
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                            mWifiP2pManager.requestDeviceInfo(mChannel) { device ->
                                device?.let {
                                    mWifiDirectActionListener.onSelfDeviceAvailable(device)
                                    if (device.status ==  WifiP2pDevice.CONNECTED){
                                        mWifiP2pManager.requestConnectionInfo(mChannel){
                                            mWifiDirectActionListener.onConnectionInfoAvailable(it)
                                        }
                                    }
                                }

                            }
                        }

                    } else {
                        mWifiDirectActionListener.wifiP2pEnabled(false)
                        val wifiP2pDeviceList: List<WifiP2pDevice> = ArrayList()
                        mWifiDirectActionListener.onPeersAvailable(wifiP2pDeviceList)
                    }
                }

                // wifi p2p设备列表发生改变 例如设备列表变化
                WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION -> {
                    Log.i(TAG, "WIFI_P2P_PEERS_CHANGED_ACTION")
                    mWifiP2pManager.requestPeers(mChannel) { peers ->
                        mWifiDirectActionListener.onPeersAvailable(
                            peers.deviceList
                        )
                    }
                }
                // wifi p2p连接状态发生改变
                WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION -> {
                    Log.i(TAG, "WIFI_P2P_CONNECTION_CHANGED_ACTION")
                    // 使用NetworkCapabilities 判断wifi p2p连接状态
                    if (ConnectivityUtil.getInstance(context).capabilities?.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED) == true &&
                        ConnectivityUtil.getInstance(context).capabilities?.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED) == true
                    ) {
                        // Wi-Fi P2P已经连接
                        mWifiP2pManager.requestConnectionInfo(mChannel) { info ->
                            if (info != null) {
                                Log.i(TAG, "确实获取到WiFip2pinfo")
                                //！！！这里很关键，只有真正的走到这里，才是真正的建立了P2P连接。拿到了准备建立Socket通道的必要信息。
                            } else {
                                Log.i(TAG, "WiFip2pinfo 为null")
                            }
                            mWifiDirectActionListener.onConnectionInfoAvailable(info)
                        }
                        Log.i(TAG, "已连接P2P")
                    } else {
                        // Wi-Fi P2P未连接
                        mWifiDirectActionListener.onDisconnection()
                        Log.i(TAG, "与P2P设备已断开连接")
                    }

                }

                //表示Wi-Fi P2P状态发生了改变：比如当前设备的WiFi状态发生了改变，或者设备的WiFi P2P状态发生了改变
                WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION -> {
                    Log.i(TAG, "WIFI_P2P_THIS_DEVICE_CHANGED_ACTION, intent:${intent.data}")
                    val device: WifiP2pDevice? = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                        intent.getParcelableExtra(
                            WifiP2pManager.EXTRA_WIFI_P2P_DEVICE, WifiP2pDevice::class.java
                        ) as WifiP2pDevice

                    } else {
                        intent.getParcelableExtra<Parcelable>(
                            WifiP2pManager.EXTRA_WIFI_P2P_DEVICE
                        ) as WifiP2pDevice

                    }

                    if (device != null) {

                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                            mWifiP2pManager.requestDeviceInfo(mChannel) { deviceInfo: WifiP2pDevice? ->
                                Log.d(TAG, "onReceive: $deviceInfo")
                                mWifiDirectActionListener.onSelfDeviceAvailable(deviceInfo)
                            }
                        }
                    }
                }

                else -> {}
            }
        }
    }

    companion object {
        private const val TAG = "DirectBroadcastReceiver"
        val intentFilter: IntentFilter
            get() {
                val intentFilter = IntentFilter()
                intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION)
                intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION)
                intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION)
                intentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION)
                return intentFilter
            }
    }
}